<?php

// ------------------------------------------------------------------------
// |@Author       : Jarmin <topextend@qq.com>
// |@----------------------------------------------------------------------
// |@Date         : 2025-05-09 18:12:10
// |@----------------------------------------------------------------------
// |@LastEditTime : 2025-05-14 02:09:10
// |@----------------------------------------------------------------------
// |@LastEditors  : Jarmin <topextend@qq.com>
// |@----------------------------------------------------------------------
// |@Description  :
// |@----------------------------------------------------------------------
// |@FilePath     : SystemService.php
// |@----------------------------------------------------------------------
// |@Copyright (c) 2025 http://www.ladmin.cn All Rights Reserved.
// ------------------------------------------------------------------------
declare (strict_types=1);

namespace think\admin\service;

use think\admin\Service;
use think\admin\repository\SystemRepository;

/**
 * 系统服务
 * Class SystemService
 * @package think\admin\service
 */
class SystemService extends Service
{
    /**
     * 系统初始化
     * @return void
     */
    public function initialize(): void
    {
        $this->repository = new SystemRepository($this->app);
    }

    /**
     * 加载系统配置
     * @return array
     */
    public function loadConfig(): array
    {
        $config = $this->repository->getConfig();
        if (!empty($config)) {
            $this->app->config->set($config, 'system');
        }
        return $this->app->config->get('system');
    }

    /**
     * 设置系统配置
     * @param string $key 配置键名
     * @param mixed $value 配置值
     * @return int
     */
    public function setConfig(string $key, mixed $value, string $code = 'basic'): int
    {
        // 1. 更新数据库
        $dbResult = $this->repository->setConfig($key, $value, $code);

        if ($dbResult) {
            // 2. 更新内存中的运行时配置
            $systemConfigs = $this->app->config->get('system');
            if (!is_array($systemConfigs)) {
                $systemConfigs = [];
            }
            if (!isset($systemConfigs[$code]) || !is_array($systemConfigs[$code])) {
                $systemConfigs[$code] = [];
            }
            $systemConfigs[$code][$key] = $value;
            $this->app->config->set($systemConfigs, 'system');
        }
        return $dbResult;
    }
}
